package com.example.demo.controller;

import com.example.demo.config.jwt.JWTUtil;
import com.example.demo.entity.user.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import com.example.demo.config.AESUtil;
import com.example.demo.config.Result;
import com.example.demo.entity.user.InsertUser;
import com.example.demo.service.LogService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;

import java.util.List;

@Tag(name = "Log API", description = "日志管理")
@RestController
@RequestMapping("/log")
public class LogController {
    @Value("${aes.secretKey}")
    byte[] aesSecretKey;
    @Autowired
    private LogService logService;

    @Operation(summary = "登录", tags = "Log API")
    @RequestMapping(value = "/login", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
    public Result login(@RequestBody InsertUser insertUser) {

        try {
            if (insertUser.getName() == null || insertUser.getName().trim().isEmpty()
                    || insertUser.getPassword() == null || insertUser.getPassword().trim().isEmpty()) {
                return Result.paramError("用户名或密码不能为空");
            }
            String decryptedData = AESUtil.decrypt(insertUser.getPassword());
            insertUser.setPassword(AESUtil.mdEncryption(decryptedData));
            List<UserInfo> user = logService.login(insertUser);
            if (user.size() > 0) {
                user.get(0).setToken(JWTUtil.getCreateToken(insertUser.getName(), 30));
                return Result.success( user.get(0));
            } else {
                return Result.error("登录失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("Decryption failed");
        }

    }



}
